#include "kernel/types.h"
#include "user/user.h"

int main(int argc, char* argv[]) {
    int p[2];

    //child process
    pipe(p);
    if (fork() == 0) {
        close(0);
        dup(p[0]);

        close(p[0]);
        close(p[1]);

        char buf[64];
        read(0, buf, sizeof(buf));  //subprocess will wait for the writing data to one end of the pipe

        printf("child process: ");
        printf(buf);

        exit(0);    //remeber to exit, otherwise will fork again (line: 37)
    }
    else {
        //can not wait, will block main process(the subprocess is not written 😂)
        //wait(0);

        close(p[0]);
        write(p[1], "Hello! This is write side end of the pipe!\n", 43);
        close(p[1]);

        wait(0);
    }

    //child process for exec
    pipe(p);
    if (fork() == 0) {
        close(0);
        dup(p[0]);

        close(p[0]);
        close(p[1]);

        char* argvec[] = {
            "zjq_1.3Pipes_exec",
            0
        };
        exec("zjq_1.3Pipes_exec", argvec);  //zjq_1.3Pipes_exec will read standard input (fd = 0)

        exit(0);
    }
    else {
        close(p[0]);
        write(p[1], "Hello! zjq_1.3Pipes_exec process!\n", 34);
        close(p[1]);
        wait(0);
    }

    exit(0);
}